package com.zhl.media.commonsdk.utils;

import android.content.Context;
import android.media.MediaPlayer;


import java.io.IOException;


public class VoiceUtils {
    private static Player player;
    private static MediaPlayer mediaPlayer;
    public static boolean isStart;
    public static String playUrl;

    public static Player getPlayer() {
        if (player == null) {
            player = new Player();
        }
        return player;
    }


    public static void play(String url) {
        playUrl = url;
        if (isStart && (url.equals(playUrl))) {
            stopVoice();
            isStart = false;
            if (player != null) {
                player.pause();
            }
            return;
        }
        isStart = true;
        getPlayer().playUrl(playUrl);
    }

    public static void playLocal(Context context, String file) {
        if (isStart) {
            stopVoice();
            isStart = false;
            return;
        }
        isStart = true;
        stopVoice();
        mediaPlayer = new MediaPlayer();
        try {
            mediaPlayer.setDataSource(file);
            mediaPlayer.prepare();
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mediaPlayer) {
                    isStart = false;
                }
            });
            mediaPlayer.start();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //停止播放声音
    public static void stopVoice() {
        if (null != mediaPlayer) {
            mediaPlayer.stop();
            mediaPlayer = null;
        }
    }
}
